//
//  SearchViewController.m
//  caishuitong
//
//  Created by qiysoft on 2017/3/27.
//  Copyright © 2017年 zhangxy. All rights reserved.
//

#import "SearchViewController.h"
//#import "SearchResultViewController.h"
#import "SearchModel.h"
#import "SearchContentViewController.h"
#import "TagView.h"
#import "CheckNetwork.h"

@interface SearchViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate,TagViewDelegate>{
    
    NSMutableArray *arrMkey;
    UIView *historyView;

}
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)UITextField *textField;
@property (nonatomic, strong)NSMutableArray *ReMenListArray;
@property (nonatomic, strong)NSMutableArray *HotArray;
@property (nonatomic ,strong)TagView * tagView;

@end

@implementation SearchViewController

- (UITableView *)tableView {

    if (_tableView == nil) {
        if ([UIScreen mainScreen].bounds.size.height == 812) {//iPhone X(需要)
            _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 70+44+self.tagView.size.height+44+90, WSCREENH_WIDTH, WSCREENH_HEIGHT - (70+44+self.tagView.size.height+44)-100) style:UITableViewStylePlain];
        }else {
            _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 70+44+self.tagView.size.height+44+90, WSCREENH_WIDTH, WSCREENH_HEIGHT - (70+44+self.tagView.size.height+44)) style:UITableViewStylePlain];
        }
        _tableView.delegate = self;
        _tableView.dataSource = self;
        self.tableView.estimatedRowHeight =0;
        self.tableView.estimatedSectionHeaderHeight =0;
        self.tableView.estimatedSectionFooterHeight =0;
        _tableView.showsVerticalScrollIndicator = YES;
        _tableView.bounces = YES;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    if (XIPHONE) {
        _BkViewTop.constant = 70+20;
    }
    
    [self initSearchView];
    [self SearchVCDataRequest];
//    [self setBtnAttribute];
    _ReMenListArray = [NSMutableArray array];
    _HotArray = [NSMutableArray array];
    arrMkey = [NSMutableArray array];

}
- (void)bigDelete {
    WLog(@"全删除");
    [WShareUtil removeDataWithUserDefaultsForKey:@"arrMkey"];
    [arrMkey removeAllObjects];
    [_tableView reloadData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES; //影藏nav
    [_textField becomeFirstResponder]; // 第一响应

    [arrMkey removeAllObjects];
    NSArray *arr = [[NSUserDefaults standardUserDefaults] objectForKey:@"arrMkey"];
    // 利用keyValue的方式数组去重
    arr = [arr valueForKeyPath:@"@distinctUnionOfObjects.self"];
    
    if (arr.count > 0) {
        [arrMkey addObjectsFromArray:arr];
    }
    
    [self.tableView reloadData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [_textField resignFirstResponder]; // 取消第一响应
//    _textField.text = [WShareUtil sharedData].searchContent;
    self.navigationController.navigationBarHidden = NO; //显示nav

}

- (void)LSSSVIEW_TABVIEW {
    if ([UIScreen mainScreen].bounds.size.height == 812) {//iPhone X(需要)
        historyView = [[UIView alloc]initWithFrame:CGRectMake(0, 70+44+self.tagView.size.height+44, WSCREENH_WIDTH, 44)];
    }else {
        historyView = [[UIView alloc]initWithFrame:CGRectMake(0, 70+44+self.tagView.size.height+44, WSCREENH_WIDTH, 44)];
    }
    // 历史搜索View
    historyView.backgroundColor = [UIColor whiteColor];
    
    // 垃圾篓按钮
    UIButton *bigDelete = [UIButton buttonWithType:UIButtonTypeCustom];
    bigDelete.frame = CGRectMake(WSCREENH_WIDTH - 50, 0, 40, 40);
    [bigDelete setImage:[UIImage imageNamed:@"bigDelete"] forState:UIControlStateNormal];
//    bigDelete.backgroundColor = [UIColor redColor];
    [bigDelete setImageEdgeInsets:UIEdgeInsetsMake(8, 8, 8, 8)];
//    [bigDelete setBackgroundImage: forState:UIControlStateNormal];
    [bigDelete addTarget:self action:@selector(bigDelete) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *lbTitle = [[UILabel alloc]initWithFrame:CGRectMake(12, 7, 150, 30)];
    lbTitle.text = @"历史搜索";
    lbTitle.font = [UIFont systemFontOfSize:15];
    lbTitle.textColor = [UIColor colorWithRed:0.62 green:0.62 blue:0.62 alpha:1];
    
    UILabel *lbLine = [[UILabel alloc]initWithFrame:CGRectMake(12, 40, WSCREENH_WIDTH-24, 1)];
    lbLine.backgroundColor = [UIColor colorWithRed:0.62 green:0.62 blue:0.62 alpha:1];
    
    [historyView addSubview:bigDelete];
    [historyView addSubview:lbTitle];
//    [historyView addSubview:lbLine];

    [self.view addSubview:historyView];
    [self.view addSubview:self.tableView];
}

- (void)initSearchView {
    // tf下的view
    UIView *searchView;
    if ([UIScreen mainScreen].bounds.size.height == 812) {//iPhone X（不需要）
        searchView = [[UIView alloc]initWithFrame:CGRectMake(10, 44, WSCREENH_WIDTH - 80, 30)];
    }else {
        searchView = [[UIView alloc]initWithFrame:CGRectMake(10, 27, WSCREENH_WIDTH - 80, 30)];
    }
    searchView.backgroundColor = [UIColor colorWithRed:0.92 green:0.92 blue:0.92 alpha:1];
    searchView.layer.cornerRadius = 15;
    
    UIImageView *ampImgView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 7, 15, 15)];
    UIImage *ampImage = [UIImage imageNamed:@"WenBa_1"];//初始化图像视图
    [ampImgView setImage:ampImage];
    
    _textField = [[UITextField alloc]initWithFrame:CGRectMake(30, 0, WSCREENH_WIDTH - 120, 30)];
    _textField.placeholder = @"请输入您的问题";
    [_textField setValue:[UIFont boldSystemFontOfSize:15] forKeyPath:@"_placeholderLabel.font"];
    _textField.font = [UIFont systemFontOfSize:15];
    _textField.delegate = self;
    [searchView addSubview:ampImgView];
    [searchView addSubview:_textField];
    
    // 添加取消按钮
    UIButton *qxBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    
    if ([UIScreen mainScreen].bounds.size.height == 812) {//iPhone X（不需要）
        qxBtn.frame = CGRectMake(WSCREENH_WIDTH -60, 44, 50, 30);
    }else {
        qxBtn.frame = CGRectMake(WSCREENH_WIDTH -60, 27, 50, 30);
    }
    [qxBtn setTitle:@"取消" forState:UIControlStateNormal];
    qxBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [qxBtn setTitleColor:[UIColor colorWithRed:0.27 green:0.6 blue:0.9 alpha:1] forState:UIControlStateNormal];
    [qxBtn addTarget:self action:@selector(quxiao) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:searchView];
    [self.view addSubview:qxBtn];

}
- (void)quxiao {
    
    [self.navigationController popViewControllerAnimated:NO];
}

// 点击搜索按钮
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    WLog(@"搜索");
    if ([_textField.text checkInputMsg]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:ALERT_TITLE message:@"请输入关键字" delegate:nil cancelButtonTitle:SURE otherButtonTitles:nil];
        [alert show];
        return YES; 
    }
    
    CheckNetwork *checkNetwork = [[CheckNetwork alloc] init];
    if (![checkNetwork isNetworkReachable]) {//没网
        return YES;
    } else {
        
        SearchContentViewController *scVC = [[SearchContentViewController alloc]init];
        scVC.keyword = _textField.text;
        [self.navigationController pushViewController:scVC animated:YES];
        
        [arrMkey addObject:textField.text];
        
        [self saveSearchHistory];
        [textField resignFirstResponder];
        
        return YES;
    }
    

}

// 保存搜索词
- (void)saveSearchHistory {
    [[NSUserDefaults standardUserDefaults] setObject:arrMkey forKey:@"arrMkey"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [_textField resignFirstResponder];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [_textField resignFirstResponder];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [arrMkey count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 40;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *identCell = @"HomeListCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identCell];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] init];
        // 文字
        UILabel *lbTitle = [[UILabel alloc]initWithFrame:CGRectMake(12, 5, WSCREENH_WIDTH - 100 + 45, 30)];
        lbTitle.text = arrMkey[indexPath.row];
        // 分割线
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(13, 39, WSCREENH_WIDTH-26, 1)];
        lineView.backgroundColor = [UIColor colorWithRed:0.91 green:0.91 blue:0.93 alpha:1];
        // 删除按钮
        UIButton *smallDelete = [UIButton buttonWithType:UIButtonTypeCustom];
        smallDelete.tag = indexPath.row;
        smallDelete.frame = CGRectMake(WSCREENH_WIDTH - 50, 0, 40, 40);
        [smallDelete setImage:[UIImage imageNamed:@"smallDelete"] forState:UIControlStateNormal];
        [smallDelete setImageEdgeInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
//        smallDelete.backgroundColor = [UIColor redColor];
//        [smallDelete setBackgroundImage:[UIImage imageNamed:@"smallDelete"] forState:UIControlStateNormal];
        [smallDelete addTarget:self action:@selector(smallDelete:) forControlEvents:UIControlEventTouchUpInside];

        [cell addSubview:lbTitle];
        [cell addSubview:lineView];
        [cell addSubview:smallDelete];
    }
    
    return cell;
}
- (void)smallDelete:(UIButton *)sender{
    WLog(@"小删除");
    
    [arrMkey removeObjectAtIndex:sender.tag];
    [WShareUtil removeDataWithUserDefaultsForKey:@"arrMkey"];
    [WShareUtil saveDataWithUserDefaultsSetObject:arrMkey ForKey:@"arrMkey"];
    [_tableView reloadData];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    CheckNetwork *checkNetwork = [[CheckNetwork alloc] init];
    if (![checkNetwork isNetworkReachable]) {//没网
        return;
    } else {
        SearchContentViewController *scVC = [[SearchContentViewController alloc]init];
        scVC.keyword = arrMkey[indexPath.row];
        [self.navigationController pushViewController:scVC animated:YES];
    }
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    
    textField.returnKeyType = UIReturnKeySearch;
}

#pragma mark - 热门搜索数据
- (void)SearchVCDataRequest {
    //mode:native,service:fwwb,content:{revert:hot}
    NSDictionary *parametersDict = @{@"mode":@"native",@"service":@"fwwb",@"content":@{@"revert":@"hot"}};
    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];
    //    NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:secret]};
    
    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];
        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];
     
        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];
        NSArray *returnArr = returnDic[@"hot"];

        WLog(@"返回数组%@",returnArr);
        for (NSDictionary *dic in returnDic[@"hot"]) {
            SearchModel *searchModel = [SearchModel mj_objectWithKeyValues:dic];
            [self.ReMenListArray addObject:searchModel];
        }
        for (int i = 0; i < returnArr.count; i++) {
            [_HotArray addObject:returnDic[@"hot"][i][@"title"]];
        }
        WLog(@"热门title数组-%@",_HotArray);
        
        [self.BKView addSubview:self.tagView];
        self.tagView.arr = _HotArray;
        [self LSSSVIEW_TABVIEW];

    } failure:^(NSError *error) {
        WLog(@"失败");
    } showProgress:YES];
    
}

-(TagView *)tagView{
    if (!_tagView) {
        _tagView = [[TagView alloc]initWithFrame:CGRectMake(0, 45, WSCREENH_WIDTH, 0)];
        _tagView.backgroundColor = [UIColor whiteColor];
        _tagView.delegate = self;
    }
    return _tagView;
}


#pragma mark - CCTagViewDelegate
-(void)handleSelectTag:(NSString *)keyWord{
    WLog(@"keyWord ---- %@",keyWord);
    
    CheckNetwork *checkNetwork = [[CheckNetwork alloc] init];
    if (![checkNetwork isNetworkReachable]) {//没网
        return;
    } else {
        SearchContentViewController *scVC = [[SearchContentViewController alloc]init];
        scVC.keyword = keyWord;
        [self.navigationController pushViewController:scVC animated:YES];
    }

}

@end
